<?php
require_once("../libs/gens/ModelCodeGenerator.class.php");

class CodeGenerator{
    public $model_defs_dir;
    public $root_dir;
   
    function __construct($root_dir,$model_defs_dir){
        $this->root_dir = $root_dir;
        $this->model_defs_dir = $model_defs_dir;
    }
    function genCode($paths=""){
        if(!$paths) $paths = "";
        $dir = $this->model_defs_dir."/".$paths;
        if ($dh = opendir($dir)) {
            while (($filename = readdir($dh)) !== false) {
                if($filename=="." || $filename==="..") continue;
                $fileFullname = $dir . $filename;
                if(filetype($fileFullname)=="dir") {
                    $target_dir = $this->root_dir.$paths;
                    if(!is_dir($target_dir)) mkdir($target_dir);
                    $this->genCode($paths."/".$filename);
                }
                $clsname = $user = strstr($filename, '.model.json', true);
                if(!$clsname) continue;
                $target_filename = $this->root_dir."/$paths/".$clsname.".generated.php";
                $jsonText =  file_get_contents($fileFullname);
                $json = json_decode($jsonText,true);
                $ns = str_replace("/","\\",$paths);
                $gener = new ModelCodeGenerator($this->root_dir,$json,$clsname,$ns);
                $mcode = $gener->genGenerated();
                file_put_contents($target_filename,$mcode);
            }
            closedir($dh);
        }
    }
}

$gen = new CodeGenerator(__DIR__."/..",__DIR__."/../model_defs");
$gen->genCode();

